Completed
Push — master ( c8cc0a...f17656 )
by Thomas
44s
created

module.exports.startChildProcess   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
c 0
b 0
f 0
nc 5
dl 0
loc 16
rs 8.2222
nop 1
1
'use strict'
2
3
const output = require('./output')
4
const Container = require('./containers/Container')
5
const fs = require('fs')
6
const io = require('socket.io-client')
7
const tmp = require('tmp')
8
const pkg = require('../package.json')
9
const path = require('path')
10
const chalk = require('chalk')
11
const moment = require('moment')
12
const request = require('./util').request
13
const child = require('./util/ChildProcess')
14
const Module = require('./containers/Module')
15
const archiver = require('archiver')
16
const filesize = require('file-size')
17
18
module.exports = {
19
  uploadFile: function (containerToken, event, path, cb, spinner) {
20
    var r = request(containerToken + '/fs', {
21
      'action': event,
22
      'name': path
23
    }, {
24
      'Content-Type': 'multipart/form-data'
25
    })
26
27
    if (event === 'add' || event === 'change' || event === 'zipBall') {
28
      r = r.attach('file', path)
29
    }
30
31
    var self = this
32
    return r.end(function (response) {
33
      if (response.body && response.body === 'Error: invalid container') {
34
        Container.clean()
35
        var func = spinner || output.err
36
        func('Container ' + containerToken + ' does not exist anymore. We cleaned your local environment, so that you can start with a clean container.')
37
        process.exit()
38
      }
39
      if (cb) {
40
        cb(response.body || '')
41
        return
42
      }
43
      if (response.body) {
44
        if (response.body.indexOf('Error:') === 0) {
45
          output.err(response.body)
46
        } else {
47
          self.logSyncMessage(response.body)
48
        }
49
      }
50
    })
51
  },
52
53
  logMessage: function (data, ret) {
54
    var message =
55
      chalk.bold(chalk[data.color](data.component)) + ' ' +
56
      data.message
57
58
    if ('time' in data) {
59
      if (data.time === 'now') {
60
        data.time = (new Date()).getTime() / 1000
61
      }
62
      message += ' ' + chalk.dim(moment(data.time * 1000).format('hh:mm:ss'))
63
    }
64
65
    if (ret) {
66
      return message
67
    }
68
69
    return output.log(message)
70
  },
71
72
  logSyncMessage: function (message, ret) {
73
    return this.logMessage({
74
      component: 'Sync',
75
      color: 'green',
76
      message: message,
77
      time: 'now'
78
    }, !!ret)
79
  },
80
81
  createInitialZip: function (dir, containerToken, envr, cb) {
82
    if (fs.existsSync(path.join(dir, 'vendor'))) {
83
      output.warn('Ignoring directory \'vendor\'')
84
    }
85
    if (fs.existsSync(path.join(dir, 'node_modules'))) {
86
      output.warn('Ignoring directory \'node_modules\'')
87
    }
88
    if (fs.existsSync(path.join(dir, 'web/node_modules'))) {
89
      output.warn('Ignoring directory \'web/node_modules\'')
90
    }
91
92
    var zipName = tmp.tmpNameSync({})
93
    var spinner = output.wait(this.logSyncMessage('Creating initial zipball', true))
94
    var zipFile = fs.createWriteStream(zipName)
95
    var self = this
96
97
    zipFile.on('close', function () {
98
      // Upload file to api.sadev.io
99
      fs.stat(zipName, function (err, stat) {
100
        if (err) {
101
          spinner('Error creating zipball')
102
          process.exit()
103
        }
104
105
        spinner()
106
107
        var size = filesize(stat.size).human('si')
108
        var stopSpinner = output.wait(self.logSyncMessage('Uploading initial zipball (' + size + ')', true))
109
110
        try {
111
          self.uploadFile(containerToken, 'zipBall', zipName, function (responseBody) {
112
            fs.unlink(zipName, function () {})
113
            if (responseBody.indexOf('OK') !== 0) {
114
              stopSpinner(responseBody || 'Could not connect to server (empty response)')
115
              process.exit()
116
            }
117
            stopSpinner(true)
118
            cb()
119
          }, spinner)
120
        } catch (e) {
121
          stopSpinner(e.message)
122
        }
123
      })
124
    })
125
126
    var archive = archiver('zip', {
127
      store: true
128
    })
129
    archive.on('error', function (err) {
130
      output.err(err)
131
    })
132
    archive.pipe(zipFile)
133
    archive.glob(path.join(dir, '**'), {
134
      ignore: ['.inc/**', '.git/**', 'node_modules', 'web/node_modules', 'node_modules/**', 'web/node_modules/**', 'vendor/**', '.gitignore', '.jshintrc']
135
    })
136
    archive.finalize()
137
  },
138
139
  startChildProcess: function () {
140
    Module.getManifest(function (manifest) {
141
      if (!('scripts' in manifest) || typeof manifest.scripts !== 'object') {
142
        return
143
      }
144
      if (!('run' in manifest.scripts) || !('length' in manifest.scripts.run)) {
145
        return
146
      }
147
148
      for (var x in manifest.scripts.run) {
149
        if (!manifest.scripts.run.hasOwnProperty(x)) {
150
          continue
151
        }
152
        var script = manifest.scripts.run[x]
153
        child.run(script)
154
      }
155
    })
156
  },
157
158
  startWebSocket: function (containerToken) {
159
    var socket = io('http://ws.sadev.io/')
160
    var self = this
161
162
    socket.on('connect', function () {
163
      socket.emit('room', 'SADEV:' + containerToken)
164
      socket.emit('room', 'BROADCAST')
165
      socket.emit('room', pkg.name + '/' + pkg.version)
166
      socket.emit('clientInfo', pkg)
167
    })
168
169
    socket.on('log', function (data) {
170
      if (!('color' in data)) {
171
        if (data.component === 'Logger') {
172
          data.color = 'yellow'
173
        } else {
174
          data.color = 'blue'
175
        }
176
      }
177
      self.logMessage(data)
178
    })
179
180
    socket.on('disconnect', function () {
181
      socket.close()
182
      setTimeout(function () {
183
        self.startWebSocket(containerToken)
184
      }, 200)
185
    })
186
187
    socket.open()
188
  }
189
190
}
191